//
//  CarVinAuthOCRVC.m
//  New_Runway
//
//  Created by mack on 2018/3/27.
//  Copyright © 2018年 NelsonJ. All rights reserved.
//

#import "CarVinAuthOCRVC.h"
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>
#import "UIImage+info.h"
#import "YTServerAPI.h"
#import "UIAlertController+Extend.h"

@interface CarVinAuthOCRVC ()<UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *codeHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHeight;
@property (weak, nonatomic) IBOutlet UIButton *takePhoto;
@property (weak, nonatomic) IBOutlet UILabel *remindL;
@property (weak, nonatomic) IBOutlet UIButton *runBtn;
@property (weak, nonatomic) IBOutlet UIButton *vinBtn;

@property (nonatomic, strong) AVCaptureSession *session;/**< 输入和输出设备之间的数据传递 */
@property (nonatomic, strong) AVCaptureDeviceInput *videoInput;/**< 输入设备 */
@property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput;/**< 照片输出流 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;/**< 预览图片层 */
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, assign) BOOL isRun;
@property (weak, nonatomic) IBOutlet UIView *picrureView;
// 摄像头设备
@property (nonatomic,strong) AVCaptureDevice *device;
// 是否打开手电筒
@property (nonatomic,assign,getter = isTorchOn) BOOL torchOn;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *center;
@end

@implementation CarVinAuthOCRVC                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
{
    CGRect _imageRect;
    NSString *_carNum;
    NSString *_time;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.bottomHeight.constant = 120 + self.BotH;
    self.navigationBarView.titleLabel.text = @"VIN码识别";
    self.navigationBarView.backgroundColor = [UIColor blackColor];
     self.navigationBarView.lineView.backgroundColor =[UIColor blackColor];
    self.isRun = NO;
    self.runBtn.selected = NO;
    self.vinBtn.selected = YES;
    [self.runBtn setTitleColor:UIColorHex(0xffc516) forState:UIControlStateSelected];
    [self.runBtn setTitleColor:kColorWhite() forState:UIControlStateNormal];
    [self.vinBtn setTitleColor:UIColorHex(0xffc516) forState:UIControlStateSelected];
    [self.vinBtn setTitleColor:kColorWhite() forState:UIControlStateNormal];
    [self.navigationBarView.rightItem setImage:[UIImage imageNamed:@"turn_off"] forState:UIControlStateNormal];
    [self checkAuthorizationStatus];
    [self initAVCaptureSession];
    self.codeHeight.constant = 80;
    _imageRect = self.picrureView.frame;
    self.center.constant = -self.BotH;
}
-(AVCaptureDevice *)device {
    if (_device == nil) {
        _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        
        NSError *error = nil;
        if ([_device lockForConfiguration:&error]) {
            if ([_device isSmoothAutoFocusSupported]) {// 平滑对焦
                _device.smoothAutoFocusEnabled = YES;
            }
            
            if ([_device isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {// 自动持续对焦
                _device.focusMode = AVCaptureFocusModeContinuousAutoFocus;
            }
            
            if ([_device isExposureModeSupported:AVCaptureExposureModeContinuousAutoExposure ]) {// 自动持续曝光
                _device.exposureMode = AVCaptureExposureModeContinuousAutoExposure;
            }
            
            if ([_device isWhiteBalanceModeSupported:AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance]) {// 自动持续白平衡
                _device.whiteBalanceMode = AVCaptureWhiteBalanceModeContinuousAutoWhiteBalance;
            }
            
            [_device unlockForConfiguration];
        }
    }
    
    return _device;
}
-(void)rightItemClick{
    self.torchOn = !self.isTorchOn;
    
    if ([self.device hasTorch]){ // 判断是否有闪光灯
        [self.device lockForConfiguration:nil];// 请求独占访问硬件设备
        
        if (self.isTorchOn) {
            
            [self.navigationBarView.rightItem setImage:[UIImage imageNamed:@"turn_on"] forState:UIControlStateNormal];
            //            self.navigationItem.rightBarButtonItem.image = [[UIImage imageNamed:@"nav_torch_on"] originalImage];
            [self.device setTorchMode:AVCaptureTorchModeOn];
        } else {
            //            self.navigationItem.rightBarButtonItem.image = [[UIImage imageNamed:@"nav_torch_off"] originalImage];
            
            [self.navigationBarView.rightItem setImage:[UIImage imageNamed:@"turn_off"] forState:UIControlStateNormal];
            [self.device setTorchMode:AVCaptureTorchModeOff];
        }
        [self.device unlockForConfiguration];// 请求解除独占访问硬件设备
    }else {
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [self alertControllerWithTitle:@"提示" message:@"您的设备没有闪光设备，不能提供手电筒功能，请检查" okAction:okAction cancelAction:nil];
    }
    
}
-(void)checkAuthorizationStatus {
    AVAuthorizationStatus authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    switch (authorizationStatus) {
        case AVAuthorizationStatusNotDetermined:[self showAuthorizationNotDetermined]; break;// 用户尚未决定授权与否，那就请求授权
        case AVAuthorizationStatusAuthorized:[self showAuthorizationAuthorized]; break;// 用户已授权，那就立即使用
        case AVAuthorizationStatusDenied:[self showAuthorizationDenied]; break;// 用户明确地拒绝授权，那就展示提示
        case AVAuthorizationStatusRestricted:[self showAuthorizationRestricted]; break;// 无法访问相机设备，那就展示提示
    }
}
#pragma mark 用户还未决定是否授权使用相机
-(void)showAuthorizationNotDetermined {
    __weak __typeof__(self) weakSelf = self;
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        granted? [weakSelf startRunning]: [weakSelf showAuthorizationDenied];
    }];
}

#pragma mark 被授权使用相机
-(void)showAuthorizationAuthorized {
    [self startRunning];
}

#pragma mark 未被授权使用相机
-(void)showAuthorizationDenied {
    NSString *title = @"相机未授权";
    NSString *message = @"请到系统的“设置-隐私-相机”中授权此应用使用您的相机";
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 跳转到该应用的隐私设授权置界面
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self leftItemClick];
        
    }];
    
    [self alertControllerWithTitle:title message:message okAction:okAction cancelAction:cancelAction];
}

#pragma mark 使用相机设备受限
-(void)showAuthorizationRestricted {
    NSString *title = @"相机设备受限";
    NSString *message = @"请检查您的手机硬件或设置";
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [self alertControllerWithTitle:title message:message okAction:okAction cancelAction:nil];
}

#pragma mark - 展示UIAlertController
-(void)alertControllerWithTitle:(NSString *)title message:(NSString *)message okAction:(UIAlertAction *)okAction cancelAction:(UIAlertAction *)cancelAction {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message okAction:okAction cancelAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)startRunning
{
    if (self.session) {
        [self.session startRunning];
    }
}

- (void)stopRunning
{
    if (self.session) {
        [self.session stopRunning];
    }
}
- (void)initAVCaptureSession {
    self.session = [[AVCaptureSession alloc] init];
    NSError *error;
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:self.device error:&error];
    if (error) {
        NSLog(@"%@", error);
    }
    // 照片输出流
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    
    // 设置输出图片格式
    NSDictionary *outputSettings = @{AVVideoCodecKey : AVVideoCodecJPEG};
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
    // 初始化预览层
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    self.previewLayer.frame = CGRectMake(0, 0, Screen_width, Screen_height);
    [self.view.layer addSublayer:self.previewLayer];
    [self.view.layer insertSublayer:self.previewLayer atIndex:0];
    [self startRunning];

}

// 获取设备方向

- (AVCaptureVideoOrientation)getOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    if (deviceOrientation == UIDeviceOrientationLandscapeLeft) {
        return AVCaptureVideoOrientationLandscapeRight;
    } else if ( deviceOrientation == UIDeviceOrientationLandscapeRight){
        return AVCaptureVideoOrientationLandscapeLeft;
    }
    return (AVCaptureVideoOrientation)deviceOrientation;
}

// 拍照
- (void)takeAPicture
{
    AVCaptureConnection *stillImageConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation];
    AVCaptureVideoOrientation avOrientation = [self getOrientationForDeviceOrientation:curDeviceOrientation];
    [stillImageConnection setVideoOrientation:avOrientation];
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        NSData *jpegData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
        UIImage *image = [UIImage imageWithData:jpegData];
        image = [UIImage image:image scaleToSize:CGSizeMake(Screen_width, Screen_height)];
        image = [UIImage imageFromImage:image inRect:_imageRect];
        [self uploadImage:image withIsrun:self.isRun];

    }];
    
}
- (void)setFrontOrBackFacingCamera:(BOOL)isUsingFrontFacingCamera {
    AVCaptureDevicePosition desiredPosition;
    if (isUsingFrontFacingCamera){
        desiredPosition = AVCaptureDevicePositionBack;
    } else {
        desiredPosition = AVCaptureDevicePositionFront;
    }
    
    for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
        if ([d position] == desiredPosition) {
            [self.previewLayer.session beginConfiguration];
            AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
            for (AVCaptureInput *oldInput in self.previewLayer.session.inputs) {
                [[self.previewLayer session] removeInput:oldInput];
            }
            [self.previewLayer.session addInput:input];
            [self.previewLayer.session commitConfiguration];
            break;
        }
    }
    
}
- (IBAction)runCode:(UIButton *)sender {
    self.codeHeight.constant = 250;
    self.remindL.text = @"请将行驶证放入框内拍照";
    self.isRun = YES;
    self.vinBtn.selected = NO;
    self.runBtn.selected = YES;
    self.navigationBarView.titleLabel.text = @"行驶证识别";
    _imageRect = self.picrureView.frame;
}
- (IBAction)VINCode:(id)sender {
    self.codeHeight.constant = 80;
    self.remindL.text = @"请将VIN码放入框内拍照";
    _imageRect = self.picrureView.frame;
    self.vinBtn.selected = YES;
    self.runBtn.selected = NO;
    self.isRun = NO;
    self.navigationBarView.titleLabel.text = @"VIN码识别";

}
- (IBAction)take:(UIButton *)sender {
    [self takeAPicture];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)uploadImage:(UIImage *)image withIsrun:(BOOL)isRun
{
    if (image) {
        NSInteger requestTag = 0;
        [SVProgressHUD show];
        
        [[YTServerAPI instance] idcardOCR:image withCardType:requestTag withIsRun:isRun callback:^(NSInteger error, NSDictionary *dic) {
            if (error == 0) {
                _carNum = dic[@"vin"];
                _time = dic[@"time"];
                if ([DataCheck isLegalHKDemailCharacterRegisterVin:_carNum] == YES) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"是否使用车架号(%@)的车辆发车？",_carNum] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                    [alert show];

                    
                }else{
                    self.getVin(_carNum, _time, NO);
                    [self stopRunning];
                    [self.navigationController popViewControllerAnimated:YES];
                    [ShowMessage showHintMessage:@"车架号错误,请手动修改或者重新识别！" duration:2.0 withRemindId:remindFail];
                }
                [SVProgressHUD dismiss];
            }else{
                [ShowMessage showHintMessage:@"识别失败!" duration:2.0 withRemindId:remindFail];
                [SVProgressHUD dismiss];

            }
            
        }];
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        self.getVin(_carNum, _time, YES);
        [self stopRunning];
        [self.navigationController popViewControllerAnimated:YES];
    }
}
-(void)leftItemClick{
    [self stopRunning];
    if (self.isOneKeyPut == YES) {
        [self.navigationController popToRootViewControllerAnimated:YES];
        
    }else{
        
        [self.navigationController popViewControllerAnimated:YES];
    }
//    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)cancelClick:(id)sender {
    [self leftItemClick];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
